package com.yoosora.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.io.ByteArrayDataInput;
import com.mikuac.shiro.annotation.MessageHandler;
import com.mikuac.shiro.bean.MsgChainBean;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.common.utils.RegexUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotPlugin;
import com.mikuac.shiro.dto.event.message.WholeMessageEvent;
import com.yoosora.common.consts.ConstsS;
import com.yoosora.model.BiliVideoApiDTO;
import com.yoosora.model.BiliVideoApiDTO.Data;
import com.yoosora.utils.BiliUtils;
import com.yoosora.utils.RegexConst;
import com.yoosora.utils.RequestUtils;
import com.yoosora.utils.Strings;
import lombok.val;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.validation.constraints.NotNull;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class BiliPlugin extends BotPlugin {
	@MessageHandler(cmd = RegexConst.BILI_LINK)
	public void biliMsg(@NotNull Bot bot, @NotNull WholeMessageEvent event){
		String message = event.getMessage();
		String build = getBuild(message,event);
		if(null != build&&Strings.isNotEmpty(build)){
			String bid = RegexUtils.regexGroup(RegexConst.BILI_BV, build, 1);
			bot.sendMsg(event, buildMessage(bid),false );
		}
	}
	public String getBuild(String message,WholeMessageEvent event){
		String msg = null;
		if(message.contains("b23.tv")){
			if (message.contains("com.tencent.miniapp_01") && message.contains("哔哩哔哩")){
				List<MsgChainBean> collect = event.getArrayMsg().stream().filter(o -> "json" .equals(o.getType())).collect(Collectors.toList());
				Map<String, String> data = collect.get(0).getData();
				JSONObject jsonObject = JSON.parseObject(data.get("data"));
				msg = (String) jsonObject.getJSONObject("meta").getJSONObject("detail_1").get("qqdocurl");
				return RequestUtils.builder().get().buildLocationStr(msg,null,null,null);
			}
			if(message.contains("CQ:xml") && message.contains("哔哩哔哩")){
				List<MsgChainBean> collect = event.getArrayMsg().stream().filter(o -> "xml" .equals(o.getType())).collect(Collectors.toList());
				Map<String, String> data = collect.get(0).getData();
				try {
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					DocumentBuilder builder = factory.newDocumentBuilder();
					Document data1 = builder.parse(new ByteArrayInputStream(data.get("data").getBytes(StandardCharsets.UTF_8)));
					NodeList nodeList = data1.getElementsByTagName("msg");
					Node item = nodeList.item(0);
					NamedNodeMap attributes = item.getAttributes();
					Node url = attributes.getNamedItem("url");
					msg = url.getNodeValue();
					return RequestUtils.builder().get().buildLocationStr(msg,null,null,null);
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}
			msg = RegexUtils.regexGroup("b23.tv/(.*)", message, 1);
			if(null != msg&&Strings.isNotEmpty(msg)){
				msg = RegexUtils.regexGroup("([a-zA-Z0-9]*)", msg, 1);
				msg = String.format("http://b23.tv/%s", msg);
				return RequestUtils.builder().get().buildLocationStr(msg,null,null,null); 
			}
		}else if(message.contains("www.bilibili.com/video/BV")){
			msg = RegexUtils.regexGroup("www.bilibili.com/video/(.*)", message, 1);
			if(null != msg&&Strings.isNotEmpty(msg)){
				msg = RegexUtils.regexGroup("([a-zA-Z0-9]*)", msg, 1);
				return String.format("https://www.bilibili.com/video/%s?", msg);
			}
		}else if(message.contains("www.bilibili.com/video/av")){
			msg = RegexUtils.regexGroup("www.bilibili.com/video/(.*)", message, 1);
			if(null != msg&&Strings.isNotEmpty(msg)){
				msg = RegexUtils.regexGroup("([a-zA-Z0-9]*)", msg, 1);
				String s = new BiliUtils().av2bv(msg);
				return String.format("https://www.bilibili.com/video/%s?", s);
			}
		}
		return null;
	}
	public String buildMessage(String bid){
		Map<String, String> param = Maps.newHashMap();
		param.put("bvid",bid);
		String result = RequestUtils.builder().get().build("https://api.bilibili.com/x/web-interface/view", null, null, param);
		BiliVideoApiDTO biliVideoApiDTO = JSON.parseObject(result, BiliVideoApiDTO.class);
		Data data = biliVideoApiDTO.getData();
		return MsgUtils.builder()
				.img(data.getPic()).text(ConstsS.N)
				.text(new StringBuilder().append(data.getTitle()).append(ConstsS.N)
				.append("UP：").append(data.getOwner().getName()).append(ConstsS.N)
				.append("播放：").append(data.getStat().getView()).append(ConstsS.N)
				.append("弹幕：").append(data.getStat().getDanmaku()).append(ConstsS.N)
				.append("投币：").append(data.getStat().getCoin())
				.append("点赞：").append(data.getStat().getLike()).append(ConstsS.N)
				.append("评论：").append(data.getStat().getReply())
				.append("分享：").append(data.getStat().getShare()).append(ConstsS.N)
				.append("https://www.bilibili.com/video/av").append(data.getStat().getAid())
				.append(ConstsS.N)
				.append("https://www.bilibili.com/video/").append(data.getBvid())
				.toString())
				.build();
	}
}
